const User = require('@/models/sys/UserModel')
const {save} = require('@/service/sys/userService')
const jwt = require('jsonwebtoken')
interface IUser {
    _id: string,
    name: string,
    password: string
}
export async function login (ctx:any) {
    const {name, password} = ctx.request.body
    const user:IUser = await User.findOne({name, password})
    if (!user) {
        ctx.throw(401, '用户名或密码不正确！')
    } else {
        const {_id, name} = user
        return new Promise((resolve, reject) => {
            jwt.sign({_id, name}, 'secret', {expiresIn:3600}, (err:any, token:string) => {
                if (err) throw err
                resolve({
                    currentAuthority: name,
                    token: 'Bearer ' + token
                })
            })
        })
    }
}

export async function regist (ctx: any) {
    const user = await save(ctx)
    return user
}